package com.rzico.sbl.ui.statistic

import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityBillDetailBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.BillWorkerData
import com.rzico.sbl.model.OrderData
import com.rzico.sbl.other.getBeforeDate
import com.rzico.sbl.other.getBeforeEndDate
import com.rzico.sbl.other.getBeforeFirstDate
import com.rzico.sbl.other.getEndDate
import com.rzico.sbl.other.getFirstDate
import com.rzico.sbl.other.getMondayDate
import com.rzico.sbl.other.getSundayDate
import com.rzico.sbl.other.getTodayDate
import com.rzico.sbl.other.getYearEndDate
import com.rzico.sbl.other.getYearFirstDate
import com.rzico.sbl.other.showBillDialog
import com.rzico.sbl.ui.order.OrderDetailActivity
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.orEmpty
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.setEmptyImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class BillDetailActivity : BaseActivity(R.layout.activity_bill_detail) {

    private val mBinding by lazy { ActivityBillDetailBinding.bind(getRootView()) }

    override fun getViewModel() = get<StatisticCommonViewModel>()

    private var mTotal = MutableLiveData(0.0)
    private var mBeginDate = ""
    private var mEndDate = ""

    override fun initData() {
        initTitle(title = "欠款明细")

        initLayout()
        initTabLayout()

        mTotal.value =
            intent
                .getExtra("amount")
                .doubleValue
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关还款记录！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            when (mPosition) {
                                0 -> getOrderData(0)
                                1 -> getRecordData(0)
                            }
                        },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    when (mPosition) {
                                        0 -> getOrderData(pageNum)
                                        1 -> getRecordData(pageNum)
                                    }
                                }
                        }
                    )
                }
            }
    }

    /**
     * 初始化 TabLayout
     */
    private fun initTabLayout() {
        mBinding
            .billTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mPosition = it.position

                            mBinding
                                .billTime
                                .root
                                .isVisible = mPosition == 0

                            when (mPosition) {
                                0 -> initOrderAdapter()
                                1 -> initRecordAdapter()
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(this.newTab().setText("历史订单"), true)
                addTab(this.newTab().setText("还款记录"), false)
            }
    }

    /**
     * 还款记录适配器
     */
    private fun initRecordAdapter() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关还款记录！"
                }

                mAdapter = SlimAdapter.creator()
                    .register<BillWorkerData>(R.layout.item_bill_record) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_bill_time, bean.create_date)
                            text(R.id.item_bill_back, bean.amount.formatDecimal())
                            text(R.id.item_bill_admin, bean.operator.orEmpty())
                        }
                    }
                    .attachTo(recycleList)

                recycleList.also {
                    (it.itemDecorationCount > 0)
                        .condition {
                            it.removeItemDecorationAt(0)
                        }
                    it.addItemDecoration(SpaceTBDecoration())
                }
            }
    }

    /**
     * 历史订单适配器
     */
    private fun initOrderAdapter() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyImg.setEmptyImage(
                        resId = R.mipmap.icon_order_no,
                        dpSize = 100f
                    )
                    it.emptyHint.text = "暂无相关订单信息！"
                }

                mAdapter = SlimAdapter.creator()
                    .register<OrderData>(R.layout.item_bill_order) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_bill_code, bean.sn)
                            text(R.id.item_bill_time, bean.createDate.getTimeString())
                            text(R.id.item_bill_num, "${bean.quantity} 件")
                            text(R.id.item_bill_amount, "${bean.amountPaid.formatDecimal()} 元")

                            clicked {
                                startActivityEx<OrderDetailActivity>("orderSn" to bean.sn)
                            }
                        }
                    }
                    .attachTo(recycleList)

                recycleList.also {
                    (it.itemDecorationCount > 0)
                        .condition {
                            it.removeItemDecorationAt(0)
                        }
                    it.addItemDecoration(SpaceTBDecoration(hasHeader = false))
                }
            }
    }

    override fun initListener() {
        mBinding
            .billTime
            .apply {
                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mAllTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "0" -> {
                                    mBeginDate = ""
                                    mEndDate = ""

                                    updateList()
                                }
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }
                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }
                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }
                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }
                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }
                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }
                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }

        mBinding
            .btBack
            .oneClick {
                showBillDialog(
                    default = mTotal.value ?: 0.0,
                    onSure = { input ->
                        if (mTotal.value!! - input.doubleValue < 0) {
                            showToast("还款金额不能超过总欠款金额")
                            return@showBillDialog
                        }

                        getViewModel()
                            .request(
                                requestUrl = BaseUrl.stsBillPay,
                                params = arrayOf(
                                    "id" to intent.getExtra("cardId"),
                                    "memberId" to intent.getExtra("memberId"),
                                    "amount" to input,
                                ),
                                onSuccess = {
                                    showToast("记账还款成功！")

                                    // 更新总欠款
                                    mTotal.value = mTotal.value!! - input.doubleValue

                                    // 更新记账列表
                                    LiveEventBus
                                        .get("billRecordList")
                                        .post("refresh")

                                    // 更新还款列表
                                    updateList()
                                }
                            )
                    }
                )
            }

        // 总欠款监听
        mTotal.observe(this) {
            mBinding
                .billTotal
                .text = it.formatDecimal()
        }
    }

    /**
     * 记账订单列表
     */
    private fun getOrderData(index: Int) {
        getViewModel()
            .billOrder(
                page = index,
                member = intent.getExtra("memberId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 记账还款列表
     */
    private fun getRecordData(index: Int) {
        getViewModel()
            .billPayList(
                page = index,
                member = intent.getExtra("memberId"),
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding.listLayout
                        .swipeRefresh
                        .isRefreshing = false
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        when (mPosition) {
            0 -> getOrderData(0)
            1 -> getRecordData(0)
        }
    }

}